// pages/coupon/buy.js
import api from '../../api/index'
import { CHINA_NORTH_REGION } from '../../store/region'
import { userInfoStore } from '../../store/userInfo'
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasRelationShop: false,
    userLevel: 0,
    pshow: false,
    cshow: false,
    dshow: false,
    plist: [],
    clist: [],
    dlist: [],
    privince: {},
    city: {},
    district: {},
    coupon: null,
    shoplist: [],
    canUseShop:[],
    selectshop: 0,
    remarks: '',
    objectArray: CHINA_NORTH_REGION,
    userCouponId:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ 
      userLevel: userInfoStore.userInfo.level,
      userCouponId: (options.userCouponId||null)
    })
    let self = this
    api.getcoupondetail({ couponId: options.couponId}).then(res=>{
      this.setData({ coupon:res.result});
    })
    // self.getuserrelationshop();
    api.getcouponcanuseshop({ couponId: options.couponId}).then(res=>{
      let { result } = res;
      if (result.length > 0) {
        self.setData({ canUseShop: result, hasRelationShop: true });
      }else{
        self.getuserrelationshop();
      }
    })

  },

  onShow: function () {
    
  },

  getuserrelationshop:function(){
    let self = this
    api.getuserrelationshop({ openId: userInfoStore.userInfo.openId }).then(res => {
      let { result } = res;
      if (result.length > 0) {
        self.setData({ shoplist: result, hasRelationShop: true });
      }
    })
  },

  getShopList:function(){
    let param = {
      province: (this.data.privince.regname ? this.data.privince.regname : ''),
      city: (this.data.city.regname ? this.data.city.regname : ''),
      district: (this.data.district.regname ? this.data.district.regname : '')
    }
    let self = this;
    api.getshoplist(param).then(res => {
      self.setData({shoplist:res.result, selectshop:0 });
    });
  },

  selectByParid:function(pid){
    let list = [];
    for (var i = 0; i < this.data.objectArray.length; i++) {
      if (this.data.objectArray[i].parid == pid) {
        list.push(this.data.objectArray[i])
      }
    }
    return list;
  },

  selectTap:function(e){
    let idx = e.currentTarget.dataset.idx;
    if (idx == 1) {
      if (!this.data.pshow){
        let list = this.selectByParid("1");
        this.setData({
          pshow: !this.data.pshow,
          plist: list,
          clist:[],
          dlist:[],
          privince: {},
          city: {},
          district: {}
        })
      } else {
        this.setData({
          pshow: !this.data.pshow
        })
      }
    }
    if (idx == 2 && this.data.privince.regid) {
      if (!this.data.cshow) {
        let list = this.selectByParid(this.data.privince.regid);
        this.setData({
          cshow: !this.data.cshow,
          clist: list,
          dlist: [],
          city: {},
          district: {}
        })
      } else {
        this.setData({
          cshow: !this.data.cshow
        })
      }
    }
    if (idx == 3 && this.data.city.regid) {
      if (!this.data.dshow) {
        let list = this.selectByParid(this.data.city.regid);
        this.setData({
          dshow: !this.data.dshow,
          dlist: list,
          district: {}
        })        
      } else {
        this.setData({
          dshow: !this.data.dshow
        })
      }
    }
  },

  optionTap: function(e) {
    
    let idx = e.currentTarget.dataset.idx;
    let index = e.currentTarget.dataset.index;
    let self = this;
    if (idx == 1) {
      this.setData({
        privince: this.data.plist[index],
        pshow: !this.data.pshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
    if (idx == 2) {
      this.setData({
        city: this.data.clist[index],
        cshow: !this.data.cshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
    if (idx == 3) {
      this.setData({
        district: this.data.dlist[index],
        dshow: !this.data.dshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
  },

  requestPayment: function (result){
    wx.requestPayment({
      'timeStamp': result.timeStamp,
      'nonceStr': result.nonceStr,
      'package': result.package,
      'signType': result.signType,
      'paySign': result.paySign,
      'success': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付成功',
          showCancel: false,
          success: (res) => {
            // wx.switchTab({
            //   url: '/pages/clickMe/index',
            // })
          }
        });
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: (res) => {
            wx.navigateBack();
          }
        });
        return;
      },
      'complete': function (res) {
        console.log('complete===', res);
      }
    });
  },

  addFreeCoupon:function(){
    let param = {
      openId: userInfoStore.userInfo.openId,
      couponId: this.data.coupon.id,
      shopId: this.data.selectshop
    };
    api.useraddfreecoupon(param).then(res => {

      wx.showToast({
        icon: "none",
        title: "已将优惠券保存至您的卡包"
      })
    }, err => {
      wx.showToast({
        icon: "none",
        title: err
      })
    })
  },

  buy: function () {
    if (this.data.coupon) {
      if (this.data.coupon.status != 1) {
        wx.showToast({
          icon: "none",
          title: "敬请期待!"
        })
        return;
      }
    }
    if (this.data.selectshop==0){
      wx.showToast({
        icon: "none",
        title: "请选择服务的商家!"
      })
      return;
    }
    if (this.data.coupon) {
      
      if (parseFloat(this.data.coupon.buyPrice)<=0){
        this.addFreeCoupon();
        return;
      }
      let param = {
        openId: userInfoStore.userInfo.openId,
        couponId: this.data.coupon.id,
        shopId: this.data.selectshop,
        amount: this.data.coupon.buyPrice,
        remarks: this.data.remarks
      }
      let self=this;
      if (this.data.userCouponId){
        param = Object.assign(param, { userCouponId: this.data.userCouponId })

        api.payCouponOrder(param).then(res => {
          let { result } = res;
          self.requestPayment(result);
        }, err => {
          wx.showToast({
            icon: "none",
            title: err
          })
        });
      } else {
        if (this.data.coupon.buyPrice == 0) {
          api.getCouponOrder(param).then(res => {
            wx.showToast({
              icon: "none",
              title: "已将优惠券保存至您的卡包"
            })
          }, err => {
            wx.showToast({
              icon: "none",
              title: err
            })
          });
        } else {
          api.getCouponOrder(param).then(res => {
            let { result } = res;
            self.requestPayment(result);
          }, err => {
            wx.showToast({
              icon: "none",
              title: err
            })
          });
        }
      }

      
    }
  },

  radioChange: function(e) {
    // console.log('radio发生change事件，携带value值为：', e.detail.value);
    this.setData({ selectshop: e.detail.value});
  },

  bindTextAreaBlur: function(e) {
    this.setData({ remarks: e.detail.value});
  }
  
})